package com.stylefeng.guns.rest.modular.wz.controller;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.WzNewsMapper;
import com.stylefeng.guns.rest.common.persistence.model.PfFile;
import com.stylefeng.guns.rest.common.persistence.model.WzNews;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWzAdv;
import com.stylefeng.guns.rest.modular.wz.service.IPfFileService;
import com.stylefeng.guns.rest.modular.wz.service.IWzAdvService;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.dom4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @program: guns-parent
 * @description: 广告预览
 * @author: Chenchao
 * @create: 2018-07-11 08:44
 **/
@Service
public class WzShareService extends ApiBaseController {
    //网页标题
    private static String headTitle;
    //广告ID
    private static Long advId;
    //广告封面图
    private static String coverUrl;
    //分享链接
    private static String shareLink;
    //iosSchema
    private static String iosSchema = "waizhuan://";
    //androidSchema
    private static String androidSchema = "waizhuan://main.app";
    //广告分享api
    private static String ADV_SHARE_API = "http://wzapp.50waizhuan.com/wz/wzShare/api";
    //公众号id
    private static String MP_WX_APPID = "wxc1614bf9f778e4d6";
    //分享描述
    private static String shareDesc = "外赚资讯";
    //banner1
    public static final String banner1 = "http://oss.50waizhuan.com/02e5c479-708e-4c24-81c5-2008f1114beb.jpg";
    //banner2
    public static final String banner2 = "http://oss.50waizhuan.com/079e649c-3cfa-4733-bef5-ac0cd9b49cad.jpg";
    //banner3
    public static final String banner3 = "http://oss.50waizhuan.com/c2ab8905-7f04-4e14-bd3d-251fbbee2f2a.jpg";
    //footbanner
    private static String footbanner = "http://oss.50waizhuan.com/429ce33b-43a0-4591-b615-6ef1d3942101.jpg";
    //ios下载链接
    private static String iosDownloadUrl = "https://itunes.apple.com/app/id1372552661";
    //安卓下载链接
    private static String androidDownloadUrl = "http://wzapp.50waizhuan.com/wz/api/v1/common/androidDownload";

    @Autowired
    private IWzAdvService wzAdvService;
    @Autowired
    private WzNewsMapper wzNewsMapper;
    @Autowired
    private IPfFileService pfFileService;


    public String createHtml(String advId,Integer subtype) throws IOException, DocumentException {
        WzNews wzNews = wzNewsMapper.selectById(advId);
        if (wzNews != null) {
            if (EnWzAdv.SUBTYPE_user_news.getIndex() == subtype) {
                String detail = wzNews.getAdvDetail();
                String avatar = wzNews.getAvatarUrl();
                if (!avatar.substring(0, 4).equals("http")) {
                    avatar = Consts.DOMAIN + avatar;
                }
                String nickName = wzNews.getNickName();
                String releastTime = DateUtil.toStringDataTime(wzNews.getReleaseTime());
                String coverurl = wzNews.getCoverUrl();
                String[] detailPic = coverurl.split(",");
                if (coverurl.split(",").length > 1) {
                    coverUrl = Consts.DOMAIN_news + coverurl.split(",")[0];
                } else {
                    coverUrl = Consts.DOMAIN_news + coverurl;
                }
                StringBuilder sb = createHtml(detail, advId, wzNews.getTitle(), subtype, avatar, nickName, releastTime, detailPic);
                AliOssUtil.putStream(new ByteArrayInputStream(sb.toString().getBytes()), advId + ".html", 5);
                PfFile file = new PfFile();
                file.setName(wzNews.getTitle());
                file.setType(6);
                file.setFileUrl(advId + ".html");
                file.setStatus(1);
                file.setBucketName(Consts.bucketName_share);
                file.setCreateTime(new Date());
                pfFileService.insert(file);
                return Consts.DOMAIN_SHARE + advId + ".html";

            }

        } else {
            return "";
        }
        return "";
    }

    public List<Map<String, Object>> dom4j(String detail) throws DocumentException, UnsupportedEncodingException {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> headMap = new HashMap<>();//head内容
        List<Map<String, Object>> tempList = new ArrayList<>();//其他内容
        Map<String, Object> Mapp = new HashMap<>();
        Document doc = DocumentHelper.parseText(detail);
        Element rootElt = doc.getRootElement();
        Iterator<Node> it = rootElt.nodeIterator();
        while (it.hasNext()) {
            Node node = it.next();
            //只有标签节点才有子节点 所以判断这个节点是否是标签节点
            if (node instanceof Element) {
                if ("head".equals(node.getName())) {
                    Element element = (Element) node;
                    Iterator<Node> itt = element.nodeIterator();
                    while (itt.hasNext()) {
                        Node nodee = itt.next();
                        if ("title".equals(nodee.getName())) {
                            headMap.put("title", ((Element) nodee).getTextTrim());
                        }
                        if ("text".equals(nodee.getName())) {
                            headMap.put("text", ((Element) nodee).getTextTrim());
                            headMap.put("style", ((Element) nodee).attributeValue("style"));
                            headMap.put("color", ((Element) node).attributeValue("color"));
                            headMap.put("font", ((Element) node).attributeValue("font"));
                        }
                        if ("image".equals(nodee.getName())) {
                            headMap.put("image", ((Element) nodee).attributeValue("src"));
                            headMap.put("size", ((Element) nodee).attributeValue("size"));
                        }
                        if ("video".equals(nodee.getName())) {
                            headMap.put("video", ((Element) nodee).attributeValue("src"));
                            headMap.put("poster", ((Element) nodee).attributeValue("thumb"));
                            headMap.put("size", ((Element) nodee).attributeValue("size"));
                        }

                    }
                } else {
                    if ("title".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("title", ((Element) node).getTextTrim());
                        tempList.add(map);
                    }
                    if ("text".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("text", ((Element) node).getTextTrim());
                        map.put("style", ((Element) node).attributeValue("style"));
                        map.put("color", ((Element) node).attributeValue("color"));
                        map.put("font", ((Element) node).attributeValue("font"));
                        tempList.add(map);
                    }
                    if ("image".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("image", ((Element) node).attributeValue("src"));
                        map.put("size", ((Element) node).attributeValue("size"));
                        tempList.add(map);
                    }
                    if ("video".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("video", ((Element) node).attributeValue("src"));
                        map.put("poster", ((Element) node).attributeValue("thumb"));
                        map.put("size", ((Element) node).attributeValue("size"));
                        tempList.add(map);
                    }
                    if ("html".equals(node.getName())) {
                        Map<String, Object> map = new HashMap<>();
                        byte[] bt = Base64Utils.decode(((Element) node).getTextTrim().getBytes());
                        String str = new String(bt, "utf-8");
                        map.put("html", str);
                        tempList.add(map);
                    }

                }

            }

        }
        Mapp.put("head", headMap);
        Mapp.put("content", tempList);
        list.add(Mapp);
        return list;
    }

    public StringBuilder createHtml(String detail, String advId, String title, Integer subtype, String avatar, String nickName, String releaseTime, String[] detailPic) throws UnsupportedEncodingException, DocumentException {
        if(Consts.dev.equals("true")){
            ADV_SHARE_API = "http://50wz.viphk1.ngrok.org/wz/wzShare/api";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html>" +
                "<html><meta charset='UTF-8'>" +
                "<meta name='apple-itunes-app' content='app-id=1372552661'/>" +
                "<meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=no' />" +
                "<meta name='apple-mobile-web-app-capable' content='yes' />" +
                "<style type='text/css'>" +
                "  * {\n" +
                "        margin: 0;\n" +
                "        padding: 0;\n" +
                "    }" +
                "    img{display:block;}" +
                "    .margin-15{margin:15px 0px 0px 0px;}" +
                "    .padding-20{padding:0px 20px 0px 20px;margin:15px 0px 0px 0px;}" +
                "    .titlefont{font-size:20px; color:#434343; line-height:34px; text-align:justify; font-weight:bold;}" +
                "    .contentfont{font-size:16px; color:#434343; line-height:26px; text-align:justify}" +
                "</style>" +
                "<body>");
        sb.append("   <div id=\"headBanner\" style=\"margin-top: 50px\">\n" +
                "        <div>\n" +
                "        <a href='javascript:;'><img src='" + banner1 + "' style='position:fixed;height: 40px;width:75.2%;top:0px'>\n" +
                "        </a>\n" +
                "        </div>\n" +
                "        <div>\n" +
                "        <a href='javascript:;' id='openApp'><img src='" + banner2 + "' style='position:fixed;height: 40px;left: 75.2%;width: 16.8%;top:0px' >\n" +
                "        </a>\n" +
                "        </div>\n" +
                "        <div >\n" +
                "        <a href='javascript:;'><img src='" + banner3 + "' style='position:fixed;height: 40px;left: 92%;width: 8%;top:0px'   onclick=\"closeThis()\">\n" +
                "        </a>\n" +
                "        </div>\n" +
                "    </div>");
        if (!"".equals(detail) && subtype != 2) {
            sb.append(
                    "<div class='padding-20'>" +
                    "<p style='font-size:22px; color:#434343; line-height:34px; text-align:justify; font-weight:bold'>" +
                    title +
                    "</p>" +
                    "</div>");
        }
        if (51 == subtype) {
            sb.append(" <div class='padding-20'><img style=\"border-radius:50%;width: 40px;height: 40px\" src=\"" + avatar + "\"> \n" +
                    "        <p style=\"padding:0px 0px 0px 0px;margin:-40px 0px 0px 51px;font-size:16px\">" + nickName + "</p>\n" +
                    "<p style=\"padding:0px 0px 0px 0px;margin:0px 0px 0px 51px;color: #878787\">" + releaseTime + "</p>" +
                    "    </div>");
        }
        if ("".equals(detail)) {
            sb.append(
                    "<div class='padding-20'>" +
                            "<p class='contentfont'>" +
                            title +
                            "</p>" +
                            "</div>");
            for (String pic : detailPic) {
                sb.append("<div class='margin-15'><span><img src='" + Consts.DOMAIN_news + pic + "' width='100%'></span></div>");
            }
        }

        if ((1 == subtype || 51 == subtype) && !"".equals(detail)) {
            List<Map<String, Object>> nodeList = dom4j(detail);
            for (int i = 0; i < nodeList.size(); i++) {
                if ("{}".equals(nodeList.get(i).get("head").toString())) {
//                    System.out.println("noneHead");
                } else {
                    Map<String, Object> map = (Map<String, Object>) nodeList.get(i).get("head");
                    if (map.get("title") != null) {
                        sb.append("<div class='padding-20'><p class='titlefont'>" + map.get("title").toString() + "</p></div>");
                    }
                    if (map.get("image") != null) {
                        sb.append("<div><span><img src='" + map.get("image").toString() + "' width='100%'></span></div>");
                    }
                    if (map.get("html") != null) {
                        sb.append(map.get("html").toString());
                    }
                    if (map.get("video") != null) {
                        sb.append("<div class='margin-15'><video style='width: 100%' poster='" + map.get("poster") + "' src='" + map.get("video").toString() + "' controls='controls'></video></div>");
                    }
                }
                if ("[]".equals(nodeList.get(i).get("content").toString())) {
//                    System.out.println("noneContent");
                } else {
                    List<Map<String, Object>> list = (List) nodeList.get(i).get("content");
                    for (Map<String, Object> map : list) {
                        if (map.get("title") != null) {
                            sb.append("<div class='padding-20'><p class='titlefont'>" + map.get("title").toString() + "</p></div>");
                        }
                        if (map.get("text") != null) {
                            sb.append("<div class='padding-20'><p class='contentfont'>" + map.get("text") + "</p></div>");
                        }
                        if (map.get("image") != null) {
//                            String margin = map.get("margin").toString();
//                            if ("true".equals(margin)) {
                            sb.append("<div class='margin-15'><span><img src='" + map.get("image").toString() + "' width='100%'></span></div>");
//                            } else {
//                                sb.append("<div><span><img src='" + map.get("image").toString() + "'  width='100%'></span></div>");
//                            }
                        }
                        if (map.get("video") != null) {
                            sb.append("<div class='margin-15'><video style='width: 100%' poster='" + map.get("poster") + "' src='" + map.get("video").toString() + "' controls='controls'></video></div>");
                        }
                        if (map.get("html") != null) {
                            sb.append(map.get("html").toString());
                        }
                    }
                }
            }
        }
        if (2 == subtype) {
            sb.append("<iframe src='' scrolling='auto' frameborder='0' width='100%' height='600'></iframe>");
        }
        sb.append("<a href='tel://0519-83621558'><div id='footbanner' class='margin-15'><img src='" + footbanner + "' width='100%'></div></a>");
        sb.append("</body></html><script src='https://code.jquery.com/jquery-3.0.0.min.js'></script>");
        if (2 == subtype) {
            sb.append("<script type='text/javascript'>" +
                    "\t$.ajaxPrefilter( function (options) {\n" +
                    "  if (options.crossDomain && jQuery.support.cors) {\n" +
                    "    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');\n" +
                    "    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;\n" +
                    "  }\n" +
                    "});\n" +
                    "\n" +
                    "var share_link=\"" + detail + "\"\n" +
                    "\t$.get(\n" +
                    "\tshare_link,\n" +
                    "\tfunction (response) {\n" +
                    "\t    console.log(\"> \", response); \n" +
                    "\t    var html = response;\n" +
                    "\t    html=html.replace(/data-src/g, \"src\"); \n" +
                    "\t    var html_src = 'data:text/html;charset=utf-8,' + html;\n" +
                    "\t    $(\"iframe\").attr(\"src\" , html_src);\n" +
                    "\t}\n" +
                    ");\n" +
                    "</script>");
        }
        sb.append("<script src=\"https://code.jquery.com/jquery-3.0.0.min.js\"></script>\n" +
                "<script src=\"https://res.wx.qq.com/open/js/jweixin-1.2.0.js\"></script>" +
                "<script type=\"text/javascript\">\n" +
                "$(\"sapn img\").attr('onclick','wzImageClick(\"{\\\\\\\"src\\\\\\\":\\\\\\\"\"+this.src+\"\\\\\\\"}\")');" +
                " function closeThis(){\n" +
                "        $(\"#headBanner\").remove();\n" +
                "    }" +
                "document.getElementById('openApp').onclick = function(e){\n" +
                "     if(navigator.userAgent.match(/(iPhone|iPod|iPad);?/i))\n" +
                "        {\n" +
                "         window.location.href ='" + iosSchema + "';//ios app协议\n" +
                "         window.setTimeout(function() {\n" +
                "             window.location.href = '" + iosDownloadUrl + "';\n" +
                "         }, 1000)\n" +
                "        }\n" +
                "     if(navigator.userAgent.match(/android/i))\n" +
                "     {\n" +
                "         window.location.href = '" + androidSchema + "';//android app协议\n" +
                "        window.setTimeout(function() {\n" +
                "             window.location.href = '" + androidDownloadUrl + "';\n" +
                "         }, 1000)    \n" +
                "     }\n" +
                " };\n" +
                "</script>" +
                "<script type=\"text/javascript\">\n" +
                "$(function() {  \n" +
                "        $.ajax({  \n" +
                "            type : \"post\",  \n" +
                "            dataType: 'json',\n" +
                "            url : '" + ADV_SHARE_API + "',  \n" +
                "            data : {  \n" +
                "                url : location.href.split('#')[0] \n" +
                "            },  \n" +
                "            complete : function() {  \n" +
                "            },  \n" +
                "            success : function(res) {  \n" +
                "                var a = res.data;\n" +
                "                var b =  a.timestamp; \n" +
                "                var c =  a.nonceStr;\n" +
                "                var d =  a.signature;\n" +
                "                    wx.config({  \n" +
                "              debug : false, //  \n" +
                "              appId : '" + MP_WX_APPID + "', // 必填，公众号的唯一标识  \n" +
                "              timestamp : a.timestamp, // 必填，生成签名的时间戳  \n" +
                "              nonceStr : a.nonceStr, // 必填，生成签名的随机串  \n" +
                "              signature : a.signature,// 必填，签名，见附录1  \n" +
                "              jsApiList : [ 'onMenuShareTimeline',  \n" +
                "                      'onMenuShareAppMessage' ]  \n" +
                "          }); \n" +
                "            }\n" +
                "        });  \n" +
                "    });  \n" +
                "  function getParamString(name) {\n" +
                "    var paramUrl = window.location.search.substr(1);\n" +
                "    var paramStrs = paramUrl.split('&');\n" +
                "    var params = {};\n" +
                "    for(var index = 0; index < paramStrs.length; index++) {\n" +
                "      params[paramStrs[index].split('=')[0]] = decodeURI(paramStrs[index].split('=')[1]);\n" +
                "    }\n" +
                "    return params[name];\n" +
                "  }\n" +
                "  \n" +
                "    var shareTitle = '" + title + "';  \n" +
                "    var shareDesc = '" + shareDesc + "';  \n" +
                "    var shareImg = '" + coverUrl + "';  \n");
//        if (type == 2) {
//            sb.append("    var url = '" + shareLink_another + advId + "&type=1&userCode='+ getParamString(\"userCode\"); \n");
//        } else {
        sb.append("    var url = '" + Consts.DOMAIN_SHARE + advId + ".html';\n");
//        }
        sb.append("    wx.ready(function() {  \n" +
                "        share();  \n" +
                "    });  \n" +
                "    function share() {  \n" +
                "        wx.showOptionMenu();  \n" +
                "        wx.onMenuShareTimeline({  \n" +
                "            title : shareTitle, // 分享标题  \n" +
                "            link : url, // 分享链接  \n" +
                "            imgUrl : shareImg,  \n" +
                "            desc : shareDesc, // 分享描述  \n" +
                "            success : function() {  \n" +
                "            }  \n" +
                "        });  \n" +
                "        wx.onMenuShareAppMessage({  \n" +
                "            title : shareTitle, // 分享标题  \n" +
                "            link : url, // 分享链接  \n" +
                "            imgUrl : shareImg,  \n" +
                "            desc : shareDesc, // 分享描述  \n" +
                "            success : function() {  \n" +
                "            }  \n" +
                "        });  \n" +
                "    }  " +
                "</script>");
        return sb;
    }

}
